package com.wpml.netty.nio.time;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class TimeClientHandle implements Runnable{

    Selector selector;
    SocketChannel client;
    volatile boolean stop;

    public TimeClientHandle() {
        try {
            selector = Selector.open();
            client = SocketChannel.open();

            client.configureBlocking(false);

        } catch (IOException e) {

            System.exit(1);
        }
    }


    @Override
    public void run() {

        try {
            doConnect();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }

        while (!stop) {
            try {
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();

                    handleInput(key);
                }


            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    private void handleInput(SelectionKey key) throws IOException {
        if (key.isValid()) {
            SocketChannel client = (SocketChannel) key.channel();
            if (key.isConnectable()) {
                if (client.finishConnect()) {
                    client.register(selector, SelectionKey.OP_READ);

                    doWrite(client);
                }
            }
            if (key.isReadable()) {
                ByteBuffer buf = ByteBuffer.allocate(1024);
                int read = client.read(buf);
                if (read > 0) {
                    buf.flip();
                    byte[] bytes = new byte[buf.remaining()];
                    buf.get(bytes);

                    String body = new String(bytes);
                    System.out.println("NOW IS : " + body);
//                    this.stop = true;
                } else if (read < 0) {
                    key.channel();
                    client.close();
                }
            }
        }
    }

    private void doWrite(SocketChannel client) {
        byte[] bytes = "QUERY TIME ORDER".getBytes();
        ByteBuffer buf = ByteBuffer.allocate(bytes.length);
        buf.put(bytes);

        buf.flip();
        try {
            client.write(buf);
            if (!buf.hasRemaining()) {
                System.out.println("发送成功");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void doConnect() throws IOException {
        if (client.connect(new InetSocketAddress("127.0.0.1", 9090))) {
            client.register(selector, SelectionKey.OP_READ);
            doWrite(client);
        } else {
            client.register(selector, SelectionKey.OP_CONNECT);
        }
    }
}
